package com.wanlian.router.ui.login;

import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextWatcher;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;

import com.smart.android.ui.app.IntentExtra;
import com.smart.android.ui.web.WebActivity;
import com.smart.android.utils.Utility;
import com.smart.android.widget.EditTextWithClear;
import com.wanlian.router.GlobalInfo;
import com.wanlian.router.MainActivity;
import com.wanlian.router.R;
import com.wanlian.router.app.AppConfig;
import com.wanlian.router.bean.User;
import com.wanlian.router.net.NetWorkingClient;
import com.wanlian.router.net.ResponseData;
import com.wanlian.router.net.internal.INetCallBack;
import com.wanlian.router.storage.AppData;
import com.wanlian.router.ui.WlBaseActivity;
import com.wanlian.router.ui.manage.RouterSettingActivity;
import com.wanlian.router.ui.router.RouterDeviceSettingActivity;

import java.util.Locale;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by Hyu on 2018/9/5.
 * Email: fvaryu@qq.com
 */
public class LoginActivity extends WlBaseActivity implements TextWatcher {

    @BindView(R.id.et_mobile)
    EditTextWithClear mMobile;
    @BindView(R.id.et_vcode)
    EditTextWithClear mVCode;
    @BindView(R.id.tv_retry)
    TextView mRetry;

    @BindView(R.id.cb_protocol)
    CheckBox mCheckBox;

    @BindView(R.id.tv_login)
    TextView mLogin;
    @BindView(R.id.tv_title)
    TextView tv_title;

    private CountDownTimer mCountDownTimer;

    @Override
    protected int layout() {
        return R.layout.activity_login;
    }

    @Override
    public void initUI() {
        super.initUI();
        setBackEnable(false);
        mMobile.addTextChangedListener(this);
        mVCode.addTextChangedListener(this);

        mCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                mLogin.setEnabled(isDataReady());
            }
        });

        setNextText("注册");
        setNextClickLisener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                redirectActivity(RegisterActivity.class);
            }
        });

        if (GlobalInfo.getInstance().getAppData().getAccount() != null) {
            mMobile.setText(GlobalInfo.getInstance().getAppData().getAccount());
        }

        SpannableString ss = new SpannableString("欢迎使用 天翼链路由器");
        ss.setSpan(new ForegroundColorSpan(Color.parseColor("#666666")), 5, ss.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        tv_title.setText(ss);
    }

    @Override
    public void initData() {
        super.initData();
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {

        mRetry.setEnabled(Utility.isMobileNO(getMobile()));
        mLogin.setEnabled(isDataReady());
    }


    @OnClick(R.id.tv_retry)
    void retry() {
        NetWorkingClient.getInstance().getVcode(getActivity(), getMobile(), new INetCallBack() {
            @Override
            public void onFinish(ResponseData response, @Nullable Object o) {
                if (response.isSuccess()) {
                    startTimer();
                    showToast("验证码已发送，请注意查收");
                }else {
                    showToast(response.getMessage());
                }
            }
        });
    }

    @OnClick(R.id.tv_login)
    void login() {

        NetWorkingClient.getInstance().login(getActivity(), getMobile(), getCode(), new INetCallBack<User>() {
            @Override
            public void onFinish(ResponseData response, @Nullable User user) {
                if (response.isSuccess() && user != null) {
                    GlobalInfo.getInstance().setUser(user);
                    GlobalInfo.getInstance().getAppData().setAccount(getMobile());
                    GlobalInfo.getInstance().getUserData().setUserId(user.getId());
                    if (user.getDevCount() > 0) {
                        redirectActivity(MainActivity.class);
                    }else {
                        Bundle bundle = new Bundle();
                        bundle.putBoolean(IntentExtra.EXTRA_BOOL, true);
                        redirectActivity(RouterDeviceSettingActivity.class, bundle);
                    }
                    finish();
                }else {
                    showToast(response.getMessage());
                }
            }
        });

    }

    private boolean isDataReady() {
        return Utility.isMobileNO(getMobile())
                && isVerCheckCode(getCode())
                && mCheckBox.isChecked();

    }

    private boolean isVerCheckCode(String s) {
        return s != null && s.length() == 6;
    }

    private String getMobile() {
        if (mMobile.getText() == null) {
            return null;
        }
        return mMobile.getText().toString();
    }

    private String getCode() {
        if (mVCode.getText() == null) {
            return null;
        }
        return mVCode.getText().toString();
    }


    private void startTimer() {
        mRetry.setEnabled(false);
        getCountDownTimer().start();
    }

    public CountDownTimer getCountDownTimer() {
        if (mCountDownTimer == null) {
            mCountDownTimer = new CountDownTimer(60 * 1000, 1000) {
                @Override
                public void onTick(long millisUntilFinished) {

                    mRetry.setText(String.format(Locale.getDefault(),
                            "%ds", millisUntilFinished / 1000));
                }

                @Override
                public void onFinish() {

                    mRetry.setText("重新获取");
                    mRetry.setEnabled(Utility.isMobileNO(getMobile()));
                }
            };
        }
        return mCountDownTimer;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mCountDownTimer != null) {
            mCountDownTimer.cancel();
            mCountDownTimer = null;
        }
    }

    @OnClick(R.id.tv_protocol_desc)
    void protocol() {
        WebActivity.fire(this, AppData.DEFAULT.get(AppConfig.USER_PROTOCOL));
    }
}
